﻿using System;
using System.Net;
using System.Security.Authentication;
using Microsoft.Practices.EnterpriseLibrary.Logging;

namespace Informant.ErrorHandling
{
	// FUTURE: This class and subclasses should log errors.
	public class BaseErrorHandler : IErrorHandler
	{
		/// <summary>
		/// Handles the error by taking application specific and external exceptions
		///	then throwing a client friendly exception, ignoring the exception.
		/// </summary>
		/// <param name="exception">The exception.</param>
		/// <exception cref="System.Security.Authentication.AuthenticationException"/>
		/// <exception cref="System.Net.WebException"/>
		/// <exception cref="System.InvalidOperationException"/>
		public virtual void MakeExceptionClientFriendly(Exception exception)
		{
			if (exception is WebException)
			{
				if (exception.Message == ErrorResources.WebExceptionForbbidenErrorMessage 
					|| exception.Message == ErrorResources.WebExceptionInternalServerErrorMessage)
				{
					Logger.Write("AuthenticationException: " + ErrorResources.AuthenticationExceptionInvalidCredentialsOrTargetServerAddress + Environment.NewLine + exception.StackTrace);
					throw new AuthenticationException(ErrorResources.AuthenticationExceptionInvalidCredentialsOrTargetServerAddress);
				}
				else
				{
					Logger.Write("WebException: " + exception.Message + Environment.NewLine + exception.StackTrace);
					throw exception;
				}
			}
			else
			{
				// Used for unknown exception types.
				Logger.Write("InvalidOperationException: " + exception.Message + Environment.NewLine + exception.StackTrace);
				throw new InvalidOperationException(exception.Message, exception);
			}
		}
	}
}
